<template>
	<view class="chat">
		<view class="flex_c page" @touchmove="touchmove">
			<view class="flex_c page" @touchmove="touchmove">
				<scroll-view class="flex1 scroll-Y" @tap.stop="onPage" id="scroll-view" lower-threshold="100" scroll-y
					scroll-with-animation :scroll-top="scroll_top" @scroll="scroll" @scrolltoupper="scrolltoupper"
					@scrolltolower="scrolltolower">
					<view :style="{ height: bottomView }"></view>
					<template v-for="(item, index) in history.messages">
						<view class="z_index2" :class="`oneheight_${index}`" style="transform: rotate(-180deg)"
							:key="index">
							<view class="icon_ text_26 color__ time">
								{{ renderMessageDate(item, index) }}
							</view>
							<!-- v-if="!item.recalled" -->
							<view :key="index">
								<item :isMy="isSelf(item.senderid)" :myid="myid" :item="item" @onClick="onItem"
									:key="history.messages.length" @onLongpress="onLongpress" @mention="mention"></item>
							</view>
							<!-- <view class="icon_ text_26 recalled" v-else>
								<view class="">
									<text v-if="isSelf(item.senderId)">你</text>
									<text v-else>{{ item.senderData.name }}</text>
									撤回了一条消息
								</view>
								<view class="recalled-edit" v-if="item.type === 'text' && isSelf(item.senderId)"
									@click="recalledEdit(item)">重新编辑</view>
							</view> -->
						</view>
					</template>

					<view :style="{ height: $store.state.StatusBar.customBar + 44 + 'px' }"></view>
				</scroll-view>
				<bottom-operation ref="bottomOperationRef" :to="to" :receiverid="receiverid" :userList="userList"
					@send="handleSend" @onBottom="onBottom" @backToBottom="bottomOperationScrollToBottom"
					@focus="focus"></bottom-operation>
			</view>
		</view>
		<m-screen-animation-lihua ref="mScreenAnimationLihua" zIndex="9999"></m-screen-animation-lihua>
		<!-- 红包雨 -->
		<m-screen-animation-hongbao ref="mScreenAnimationHongbao"></m-screen-animation-hongbao>
		<!-- 视频播放器 -->
		<video-player-ref v-model="videoPlayer.show" :url="videoPlayer.url"
			@onVideoFullScreenChange="onVideoFullScreenChange"></video-player-ref>
		<!-- 红包封面 -->
		<open-red-packet ref="openRedPacketRef"></open-red-packet>
		<!-- 复制；撤回等操作 -->
		<operate ref="operateRef" @quote="quote" @thank="thank" @transmit="transmit"></operate>
		<!-- 转发选择聊天 -->
		<m-group-selection ref="groupSelectionRef" @sendMessage="sendMessage"></m-group-selection>
	</view>
</template>

<script>
import {
	getMsgList,
	getSend,
	getMsgUser
} from "@/lib/message";
import {
	showFailure
} from '@/lib/helper';
import bottomOperation from './components/bottom-operation/index.vue';
import item from './components/item/index';
import videoPlayerRef from './components/video-player/index';
import openRedPacket from './components/open-red-packet/index';
import operate from './components/operate/index';
import {
	mapState
} from 'vuex';

let lastMessageTimeStamp = null;

let userInforMap = {};

let envelopeClickList = [];
let innerAudioContext = uni.createInnerAudioContext();
let audioItem = {};
let group = {};

// 浏览照片数组
let imageList = [];

// 是否是手动触发的列表滑动
let isBottomOperationScrollToBottom = false;
import {
	show,
	formatDate,
	throttle,
	openimg,
	getLocation,
	to as tofn
} from '@/utils/chat.js';
const IMAGE_MAX_WIDTH = 200;
const IMAGE_MAX_HEIGHT = 150;
let scroll_top = 0;
import {
	emMessages
} from '@/EaseIM/emApis';
import {
	MESSAGE_TYPE
} from '@/EaseIM/constant';
const {
	sendDisplayMessages,
	sendCommandMessages,
	modifyDisplayMessages
} = emMessages();
import eventBus from '@/utils/eventBus';
export default {
	components: {
		bottomOperation,
		item,
		videoPlayerRef,
		openRedPacket,
		operate
	},
	data() {
		return {
			chatid: "",
			isHistoryGet: false,
			bottomView: '30rpx',
			myid: null,
			scroll_top,
			userList: [], //群成员列表
			groupCount: '',
			pagueObj: {
				name: ''
			},
			to: {},
			// 历史数据
			history: {
				messages: [],
				allLoaded: false
			},
			receiverid: "",
			pageNo: 1,
			pageSize: 10,
			hasMore: false,
			userid: "",
			name:'',
			videoPlayer: {
				show: false,
				url: '',
				context: null
			}
		}
	},
	computed: mapState({
		page_font_size: (state) => state.page_font_size,
		//显示时间
		renderMessageDate() {
			return (message, index) => {
				if (message.timestamp - this.history.messages[index + 1]?.timestamp > 3 * 60 * 1000) {
					return formatDate(message.timestamp, 'timestamp');
				}
				return '';
			};
		},
		// 是否本人isMy
		isSelf() {
			return (senderid) => {
				return senderid == `${this.$store.state.user.id}`;
			};
		},
		envelope_top_opened() {
			return (id) => {
				return this.envelopeXollectionList.includes(id);
			};
		}
	}),
	async onLoad(e) {
		let _this = this;
		this.chatid = e.chatid;
		this.userid = e.userid;
		this.receiverid = e.receiverid;
		this.name = e.name;
		this.myid = this.$store.state.user.id;
		this.pageNo = 1;
		this.history.messages = [];
		this.loadHistoryMessage();
		eventBus.on('UPDATE_MESSAGE_COLLECTION', (data) => {
			console.log('有人发消息了/////////////', data)
			_this.pageNo = 1;
			_this.history.messages = [];
			_this.loadHistoryMessage();
		})
		uni.setNavigationBarTitle({
		      title: this.name
		    });
	},
	onShow() {
		let _this = this
		
	},
	onReachBottom() {
		if (this.hasMore) {
			this.pageNo = this.pageNo + 1;
			this.loadHistoryMessage();
		}
	},
	onReady() {
		this.videoPlayer.context = uni.createVideoContext('videoPlayer', this);
	},
	onNavigationBarButtonTap(e) {
		this.showMembers();
	},
	methods: {
		// 点击整个页面
		onPage() {
			this.$refs.bottomOperationRef.close();
			this.$refs.operateRef.close();
		},
		onBottom() {
			this.$refs.operateRef.close();
		},
		// 输入框获取焦点
		focus() {
			if (this.isHistoryGet) {
				this.isHistoryGet = false;
				lastMessageTimeStamp = null;
				this.history.messages = [];
				this.loadHistoryMessage();
			}
		},
		// 获取聊天记录
		loadHistoryMessage(isReset) {
			uni.hideLoading();
			this.loadStatus = 'loading';
			let obj = {
				chatid: this.chatid,
				pageNo: this.pageNo,
				pageSize: this.pageSize,
			}
			if (this.chatid) {
				obj['chatid'] = this.chatid
			}
			if (this.userid) {
				obj['userid'] = this.userid
			}
			let url = this.chatid ? getMsgList(obj) : getMsgUser(obj);
			url.then((res) => {
				console.log(res)
				uni.hideLoading();
				this.loadStatus = 'no-more';
				this.hasMore = res.data.hasMore;
				if (isReset) {
					this.history.messages = res.data.records;
				} else {
					this.history.messages = this.history.messages.concat(res.data.records);
				}
				console.log('msgList', this.history.messages)
			}).catch((res) => {
				this.loadStatus = 'no-more';
				uni.hideLoading();
			});
		},
		// 设置不足一页时占位高度
		setOneHeight() {
			this.$nextTick(() => {
				let view = uni.createSelectorQuery().select(`.oneheight_${this.history.messages.length - 1}`);
				view.boundingClientRect((data) => {
					if (!data) return;
					if (!data.top) return;
					this.bottomView = `${data.top - this.$store.state.StatusBar.customBar}px`;
				}).exec();
			});
		},
		// 滚动中
		scroll(e) {
			scroll_top = e.detail.scrollTop;
			this.$refs.operateRef.close();
			if (isBottomOperationScrollToBottom) return;
			this.$refs.bottomOperationRef.closeAll();
		},
		// 滚动到底部
		scrolltolower() {
			if (this.history.allLoaded) return;
			this.loadHistoryMessage();
		},
		// 滚动到顶部
		scrolltoupper() {

		},
		touchmove() {
			// this.$refs.bottomOperationRef.closeAll();
		},
		onMessageReceived(message) {
			if (message.chatid === group.id) {
				// push进列表
				this.pushList(message);
				//聊天时，收到消息标记为已读
				this.markGroupMessageAsRead();
			}
		},
		// 转发成功后
		// sendMessage(message) {
		// 	// push进列表
		// 	if (message.chatid === this.chatid) {
		// 		this.pushList(message);
		// 		// 同步消息到首页
		// 		uni.$emit('onMessageReceived', message);
		// 	}
		// },
		// 将信息设置为已读
		markGroupMessageAsRead() {
			//
		},
		// 发送信息后，将信息push到列表
		async handleSend(message) {
			let _this = this;
			let obj = {
				receiverid: _this.receiverid,
				content: message.type == 1 ? message.text : message.url,
				type: message.type,
			}
			if (message.type == 2) {
				obj['filename'] = message.filename;
				obj['width'] = message.width;
				obj['height'] = message.height;
			}
			if(_this.history.messages.length>0){
				let arr = _this.history.messages[0];
				arr.content = message.type == 1 ? message.text : message.url;
				arr.type = message.type;
				arr.receiverid =  _this.receiverid;
				_this.history.messages.push(arr);
			}
			getSend(obj).then((res) => {
				if (res.statusCode == 0) {
					_this.pageNo = 1;
					_this.loadHistoryMessage(true)
					_this.onSend(message)
				} else {
					_this.history.messages.shift();
					uni.showToast({
						title: res.message,
						icon: 'none'
					})
				}
			}).catch((err) => {

			})
			// 是否触发文字动效果
			if (message.type === 1) {
				this.onSetText(message.text);
			}

		},
		async onSend(message) {
			let _this = this;
			let params = {
				// 消息类型。
				type: message.type == 1 ? 'txt' : 'img',
				// 消息内容。
				msg: message.type == 1 ? message.text : message.url,
				// 消息接收方：单聊为对方用户 ID，群聊和聊天室分别为群组 ID 和聊天室 ID。
				to: _this.receiverid,
				// 会话类型：单聊、群聊和聊天室分别为 `singleChat`、`groupChat` 和 `chatRoom`。
				chatType: 'singleChat',
				ext: {},
			};
			try {
				const res = await sendDisplayMessages({ ...params });

				console.log('>>>>>文本消息发送成功', res);
			} catch (error) {
				// console.log('>>>>>文本消息发送失败', error);
				if (error.type === 508) {
					uni.showToast({
						title: '发送内容不合规',
						icon: 'none',
					});
				} else {
					//   uni.showToast({
					//     title: `消息发送失败${error.type}`,
					//     icon: 'none',
					//   });
				}
			} finally {
			}

		},

		// 文本触发效果相关========
		onSetText(text) {
			// 触发礼花
			throttle(() => {
				if (text.includes('[彩带]')) {
					this.$refs.mScreenAnimationLihua.show();
					uni.vibrateLong();
				}
			}, 4000);
		},
		// 触发红包雨
		onSetRedEnvelope() {
			throttle(() => {
				this.$refs.mScreenAnimationHongbao.show();
				uni.vibrateLong();
			}, 4000);
		},
		bottomOperationScrollToBottom() {
			isBottomOperationScrollToBottom = true;
			setTimeout(() => {
				isBottomOperationScrollToBottom = false;
			}, 800);
			this.$nextTick(() => {
				this.scrollToBottom();
			});
		},
		// 页面滚动到底部
		scrollToBottom(e) {
			this.scroll_top = scroll_top;
			this.$nextTick(() => {
				this.scroll_top = 0;
			});
		},
		// 点击某条信息
		onItem(item, index) {
			console.log(item);
			switch (item.type) {
				case 'video':
					this.playVideo(item);
					break;
				case 'audio':
					this.playAudio(item);
					break;
				case 'audio_quote':
					this.playAudio(item);
					break;
				case 2:
					const index = this.history.messages.indexOf(item.content);
					if (index === -1) return openimg(this.history.messages.length - 1, this.history.messages);
					openimg(index, this.history.messages);
					break;
				case 'red_envelope':
					// 点击红包
					const fun = (code) => {
						this.renewItem(code, item);
					};
					uni.$off('open_red_packet');
					uni.$on('open_red_packet', fun);
					item['id'] = group.id;
					this.$refs.openRedPacketRef.open(item);
					break;
				case 'map':
					getLocation({
						name: item.payload.title,
						address: item.payload.address,
						latitude: item.payload.latitude,
						longitude: item.payload.longitude
					});
					break;
				case 'article':
					tofn(`/pagesOne/HTML/index?id=${item.payload.id}`);
					break;
				case 'share_SBCF':
					tofn('/pagesSBCF/commodity_list/index', {
						id: item.payload.seller_id
					});
					break;
				case 'share_mall':
					tofn(`/pagesShopping/details/index`, {
						goods_id: item.payload.goods_id
					});
					break;
				case 'functional_module':
					tofn(item.payload.url);
					break;
				default:
					break;
			}
		},
		// 点击红包后更新那一条
		renewItem(code, item) {
			if (code === '0') {
				// 领取
				item.had_draw = 1;
			} else {
				item.isClick = 1;
			}
			// 不这样写某些情况下更新不了视图，
			for (let i = 0; i < this.history.messages.length; i++) {
				if (this.history.messages[i].messageId == item.messageId) {
					this.$set(this.history.messages, i, {
						...item
					});
					break;
				}
			}
		},
		// 长按相关=======================
		// 长按某一条
		onLongpress(item, e) {
			this.$refs.operateRef.open(item, e);
		},
		// 引用
		quote(item) {
			this.$refs.bottomOperationRef.quote(item);
		},
		// 谢谢红包
		thank(item) {
			this.$refs.bottomOperationRef.thank(item);
		},
		// 转发
		transmit(item) {
			this.$refs.groupSelectionRef.open(item);
		},
		// 重新编辑
		recalledEdit(item) {
			this.$refs.bottomOperationRef.recalledEdit(item);
		},
		// @某人
		mention(item) {
			this.$refs.bottomOperationRef.mention(item);
		},
		// 视频相关========================
		// 点击了视频并播放
		playVideo(item) {
			this.videoPlayer.url = item.payload.video.url;
			this.videoPlayer.show = true;
			this.$nextTick(() => {
				this.videoPlayer.context.requestFullScreen({
					direction: 0
				});
				this.videoPlayer.context.play();
				this.videoPlayer.context.showStatusBar();
			});
		},
		// 退出全屏
		onVideoFullScreenChange(e) {
			//当退出全屏播放时，隐藏播放器
			if (this.videoPlayer.show && !e.detail.fullScreen) {
				this.videoPlayer.show = false;
				this.videoPlayer.context.stop();
			}
		},
		// =============================================
		// 播放语音相关===========
		playAudio(item) {
			throttle(() => {
				// pause:1暂停;2播放完,3播放中,4初始状态
				if (item.messageId === audioItem?.messageId) {
					if (audioItem['pause'] == 3) {
						//正在播放
						// 暂停
						innerAudioContext.pause();
						innerAudioContext.offEnded();
						item['pause'] = 1;
						audioItem['pause'] = 1;
					} else if (audioItem['pause'] == 1 || audioItem['pause'] == 2) {
						//暂停或者播放中
						// 播放
						innerAudioContext.play();
					}
					return;
				}

				audioItem['pause'] = '4';
				audioItem = item;
				if (innerAudioContext) {
					try {
						innerAudioContext.pause();
						innerAudioContext.destroy();
						innerAudioContext = null;
					} catch (e) { }
				}
				innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.src = item.payload.url;
				innerAudioContext.play();
				innerAudioContext.offEnded();
				innerAudioContext.offPlay();
				innerAudioContext.onPlay(() => {
					// console.log('开始播放');
					item['pause'] = 3;
					audioItem['pause'] = 3;
				});
				innerAudioContext.onEnded(() => {
					// console.log('播放结束');
					item['pause'] = 2;
					audioItem['pause'] = 2;
				});
				innerAudioContext.onError((res) => {
					console.log('播放异常');
				});
			}, 500);
		},
	}
}
</script>

<style lang="scss" scoped>
.page {
	position: fixed;
	z-index: 1;
	top: 0;
	left: 0;
	bottom: 0;
	right: 0;
	background-color: #ededed;
}

.scroll-Y {
	width: 100%;
	height: 0;
	transition: all 0.2s;
	transform: rotate(180deg);
	background-color: #ededed;

	::-webkit-scrollbar {
		display: none;
	}
}

.time {
	width: 100%;
	color: #a3a3a3;
	line-height: 100rpx;
}

.recalled {
	width: 100%;
	height: 50rpx;
	margin: 20rpx 0;
	color: #a3a3a3;

	.recalled-edit {
		color: #5a6693;
		margin-left: 14rpx;
	}
}
</style>